package com.stdspringboot.ctrl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.stdspringboot.entity.Leave;
import com.stdspringboot.entity.User;
import com.stdspringboot.service.ILeaveService;
import com.stdspringboot.util.Constant;
import com.stdspringboot.util.DateUtil;
import com.stdspringboot.vo.JsonResult;
import com.stdspringboot.vo.LeaveVO;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/leave")
public class LeaveCtrl {

    @Resource
    private ILeaveService service;

    /**
     * 查询请假列表，可根据申请人查询，支持分页
     * @param applicant 申请人
     * @param pageNum 查询某页的页数
     * @param pageSize 每页显示的记录数
     * @return JsonResult
     */
    @RequestMapping("/query")
    public JsonResult query(String applicant,Integer pageNum,Integer pageSize){
        if(pageNum==null){
            pageNum=1; //当前页数
        }
        if(pageSize==null){
            pageSize=10;//意思是：每页显示10条记录
        }
        JsonResult jr=null;
        PageInfo page=service.query(applicant,pageNum,pageSize);

        jr=JsonResult.success("查询成功！",page);
        return jr;
    }

    @RequestMapping("/deleteById")
    public JsonResult deleteById(String id){

        int i=service.deleteById(id);

        JsonResult jr=null;
        if(i>0){
            jr=JsonResult.success("删除成功！");
        }else{
            jr=JsonResult.fail(JsonResult.CODE_RECORD_NO_EXIST,"记录不存在，无法删除！");
        }

        return jr;
    }
    @RequestMapping("/add")
    public JsonResult add(Leave leave, HttpSession session){

        //校验结束日期 大于等于 开始日期
        //比较日期时 ，就不能用String，用Date类型

        try{
            boolean b= DateUtil.beforeAndEquals(leave.getStartDate(), leave.getEndDate());
            if(!b){ // ! 表示取反
                return JsonResult.fail(JsonResult.CODE_START_END_DATE,"开始日期要早于结束日期，请重新填写！");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        User user=(User) session.getAttribute(Constant.KEY_SESSION_USERINFO);

//        String userId=user.getUid();
        String userId="1";
        leave.setUserId(  userId  );


        JsonResult jr=JsonResult.success("添加成功！");
        int i=service.add(leave);

        return jr;
    }

    @RequestMapping("/showById")
    public JsonResult showById(String id){
        LeaveVO leave =service.showById(id);

//        一般不要将return写在 if else的里面，不符合规范
//        if(leave==null){
//            return JsonResult.fail(JsonResult.CODE_RECORD_NO_EXIST,"该记录不存在！");
//        }else{
//            return JsonResult.success(null,leave);
//        }

        JsonResult jr=null;
        if(leave==null){
            jr= JsonResult.fail(JsonResult.CODE_RECORD_NO_EXIST,"该记录不存在！");
        }else{
            jr= JsonResult.success(null,leave);
        }
        //只在最后一步返回结果
        return jr;
    }

    @RequestMapping("/modifyById")
    public JsonResult modifyById(LeaveVO leave){

        try{
            boolean b= DateUtil.beforeAndEquals(leave.getStartDate(), leave.getEndDate());
            if(!b){ // ! 表示取反
                return JsonResult.fail(JsonResult.CODE_START_END_DATE,"开始日期要早于结束日期，请重新填写！");
            }
        }catch(Exception e){
            e.printStackTrace();
        }

        int i=service.modifyById(leave);
        JsonResult jr=null;
        if(i>0){
            jr=JsonResult.success("修改成功！");
        }else{
            jr=JsonResult.fail(JsonResult.CODE_RECORD_NO_EXIST,"没有该条记录！");
        }
        return jr;
    }
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile image, HttpServletRequest req) throws IOException {

        //防止上传文件同名，用uuid作为文件名
        String oFilename=image.getOriginalFilename();
        String suffix=oFilename.substring(oFilename.lastIndexOf("."));
        String newFilename= UUID.randomUUID().toString().replace("-","")+suffix;

        String classpath=ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath();
        File file=new File(classpath,"/static/upload/");

        //前端页面回显图片的url
        String imageURL="upload/"+newFilename;
        //由于设置的临时目录也是该目录，启动服务时，会自动创建临时目录，所以此处可以不用判断
        if(!file.exists()) {
            file.mkdirs();
        }
        File filePath=new File(file,newFilename);

        image.transferTo(filePath);
        return JsonResult.success("上传成功！",imageURL);
    }

    @RequestMapping("/add2")
    public JsonResult add2(Leave leave, @RequestParam(value = "uploadList",required = false) List uploadList){

        return JsonResult.success("添加成功！");
    }
}
